<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-08-09 13:44:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-26 10:47:17
-->
<template>
  <div>
    <a-modal v-model="visible" title="批量添加批次" @ok="handleOk" @cancel="handleClose">
      <a-form :form="form" @submit="handleOk" layout="horizontal" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18 }">
        <a-form-item label="初始工序" prop="originTaskId">
          <a-select
            placeholder="请选择"
            allowClear
            showSearch
            @change="changeTask"
            v-decorator="['originTaskId', { rules: [{ required: true, message: '请选择初始工序' }] }]"
          >
            <a-select-option v-for="option in processList" :key="option.id" :value="option.id">{{option.showName}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="报工单位" prop="processWorkUnitText">
          <a-input disabled v-decorator="['processWorkUnitText']" placeholder="请选择初始工序" />
        </a-form-item>
        <a-form-item label="编号前缀" prop="batchCodePrefix">
          <a-input v-decorator="['batchCodePrefix', { rules: [{ required: true, message: '请输入编号前缀' }] }]" placeholder="请输入" @input="beforeSubmit" />
        </a-form-item>
        <a-form-item label="自增位数" prop="numberOfDigital">
          <a-select
            placeholder="请选择"
            allowClear
            showSearch
            @change="changeDigital"
            v-decorator="['numberOfDigital', { rules: [{ required: true, message: '请选择自增位数' }] }]"
          >
            <a-select-option v-for="i in 5" :key="i" :value="i">{{ i }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="起始自增号" prop="beginNumberCode">
          <a-input
            v-decorator="['beginNumberCode', { rules: [{ required: true, message: '请输入' }, { validator: validateToStartNum }] }]"
            @input="(e) => inputStartNum(e)"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item label="添加批次数" prop="batchNum">
          <a-input
            v-decorator="['batchNum', { rules: [{ required: true, message: '请输入' }, { validator: validateToBatchNum }] }]"
            @input="(e) => inputBatchNum(e)"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item label="计划生产数" prop="planProductionNum">
          <a-input
            v-decorator="['planProductionNum', { rules: [{ required: true, message: '请输入' }, { validator: validateToNum }] }]"
            @input="(e) => inputNum(e)"
            placeholder="请输入"
          />
        </a-form-item>
      </a-form>
      <a-row :gutter="24">
        <a-col :span="5" style="padding:0">
          <div class="secondary-text" style="text-align: right">批次预览:</div>
        </a-col>
        <a-col :span="18">
          <a-tooltip>
            <template slot="title">
              {{ tipsText }}
            </template>
            <div class="secondary-text limit-text">{{ tipsText }}</div>
          </a-tooltip>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import { API } from '@/api/requestFzs'
import { messProductBatchBatchAdd, genBatchCode } from '@/api/productOrder'
import { clearNoNum, integerNum} from '@/utils/util'
export default {
  data() {
    return {
      visible: false,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      processList: [],
      orderInfo: {},
      processList: [],
      canSubmit: false,
      tipsText: '输入完编号、位数、自增号、批次数后自动显示',
      errMessage: ''
    }
  },
  methods: {
    showModal(val, list) {
      this.form.resetFields()
      this.orderInfo = val
      this.processList = list
      this.visible = true
    },
    // 选择工序
    changeTask(v) {
      if (!v) {
        this.form.setFieldsValue({
          processWorkUnitText: '',
        })
      } else {
        let task = this.processList.find(item => item.id == v)
        this.form.setFieldsValue({
          processWorkUnitText: task.processWorkUnitText,
        })
      }
    },
    // 选择自增位数
    changeDigital(v) {
      if (v) {
        this.form.setFieldsValue({
          beginNumberCode: '',
          batchNum: '',
          numberOfDigital: v
        })
      } else {
        this.form.setFieldsValue({
          beginNumberCode: '',
          batchNum: '',
        })
      }
      this.beforeSubmit()
    },
    inputStartNum(e) {
      let {numberOfDigital, batchNum} = this.form.getFieldsValue(['numberOfDigital','batchNum'])
      // let num = integerNum(e.target.value)
      let num = e.target.value.replace(/[^0-9]/g, '')
      if (!numberOfDigital) {
        this.$antdMessage.warning('请先选择自增位数')
        num = ''
      } else {
        let len = Number(numberOfDigital)
        num = num.substr(0, len)
      }
      this.form.setFieldsValue({
        beginNumberCode: num,
        batchNum: ''
      })
      // if (batchNum) {
      //   let e = { target: { value:batchNum } }
      //   this.inputBatchNum(e)
      // }
      this.beforeSubmit()
    },
    inputBatchNum(e) {
      let {numberOfDigital, beginNumberCode} = this.form.getFieldsValue(['numberOfDigital', 'beginNumberCode'])
      let num = integerNum(e.target.value)
      if (!numberOfDigital) {
        this.$antdMessage.warning('请先选择自增位数')
        this.form.setFieldsValue({ batchNum: '' })
        return
      }
      if (!beginNumberCode) {
        this.$antdMessage.warning('请先输入起始自增号')
        this.form.setFieldsValue({ batchNum: '' })
        return
      }
      let fullNum = ''
      for (let i = 0; i < Number(numberOfDigital); i++) {
        fullNum += '9'
      }
      let maxNum = Number(fullNum) - Number(beginNumberCode) + 1
      console.log(Number(fullNum),'-',Number(beginNumberCode));
      if (Number(num) > maxNum) {
        num = maxNum
      }
      this.form.setFieldsValue({
        batchNum: num,
      })
      this.beforeSubmit()
    },
    inputNum(e) {
      this.form.setFieldsValue({
        planProductionNum: clearNoNum(e.target.value),
      })
      // this.beforeSubmit()
    },
    beforeSubmit() {
      this.canSubmit = false
      this.tipsText = '输入完编号、位数、自增号、批次数后自动显示'
      let {numberOfDigital, beginNumberCode, batchNum, batchCodePrefix} = this.form.getFieldsValue(['originTaskId', 'numberOfDigital', 'beginNumberCode', 'batchNum', 'batchCodePrefix', 'planProductionNum'])
      if (numberOfDigital && beginNumberCode && batchNum && batchCodePrefix) {
        genBatchCode({
          numberOfDigital,
          beginNumberCode,
          batchNum,
          batchCodePrefix,
        }).then(res => {
          if (res.code == 200) {
            this.canSubmit = true
            if (res.result.length == 1) {
              this.tipsText = res.result[0]
            } else if (res.result.length > 1) {
              this.tipsText = `${res.result[0]}...${res.result[res.result.length-1]}`
            }
          } else {
            this.errMessage = res.message
            this.$antdMessage.error(res.message)
          }
        })
      }
    },
    /* 数量校验大于0 */
    validateToNum(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (/[1-9]+[0-9]*/.test(value)) {
        callback()
      } else {
        callback('必须大于0')
      }
    },
    validateToStartNum(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      let numberOfDigital = this.form.getFieldsValue(['numberOfDigital']).numberOfDigital
      let len = numberOfDigital ? Number(numberOfDigital) : 0
      if (value.length != len) {
        callback(`请输入${len}位数`)
      } else {
        callback()
      }
    },
    validateToBatchNum(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (/[1-9]+[0-9]*/.test(value)) {
        callback()
      } else {
        callback('必须大于0')
      }
    },
    handleOk() {
      this.form.validateFields((err, formValues) => {
        console.log(err, formValues)
        if (!err) {
          if (!this.canSubmit) {
            this.$antdMessage.error(this.errMessage)
            return
          }
          messProductBatchBatchAdd(formValues).then(res => {
            if (res.code == 200) {
              this.$antdMessage.success(res.message)
              this.$emit('refresh')
              this.handleClose()
            } else {
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    handleClose() {
      this.form.resetFields()
      this.visible = false
    },
  },
}
</script>

<style lang="less" scoped>
.code-btn {
  position: absolute;
  right: 10px;
  top: -13px;
}
</style>
